<template>
    <div v-if="showMonitor && isDev" class="performance-monitor">
        <div class="monitor-header">
            <span>性能监控</span>
            <button @click="toggleMonitor" class="toggle-btn">{{ isExpanded ? '收起' : '展开' }}</button>
        </div>

        <div v-if="isExpanded" class="monitor-content">
            <div class="metric">
                <span class="label">页面加载时间:</span>
                <span class="value">{{ loadTime }}ms</span>
            </div>

            <div class="metric">
                <span class="label">内存使用:</span>
                <span class="value">{{ memoryUsage }}MB</span>
            </div>

            <div class="metric">
                <span class="label">FPS:</span>
                <span class="value">{{ fps }}</span>
            </div>

            <div class="metric">
                <span class="label">网络状态:</span>
                <span class="value" :class="networkClass">{{ networkStatus }}</span>
            </div>

            <div class="actions">
                <button @click="clearCache" class="action-btn">清除缓存</button>
                <button @click="exportLogs" class="action-btn">导出日志</button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'

// 响应式数据
const showMonitor = ref(false)
const isExpanded = ref(false)
const loadTime = ref(0)
const memoryUsage = ref(0)
const fps = ref(0)
const networkStatus = ref('unknown')

// 计算属性
const isDev = computed(() => import.meta.env.DEV)
const networkClass = computed(() => {
    switch (networkStatus.value) {
        case 'online': return 'status-good'
        case 'offline': return 'status-bad'
        default: return 'status-unknown'
    }
})

// 性能监控变量
let frameCount = 0
let lastTime = performance.now()
let animationId: number

// 方法
const toggleMonitor = () => {
    isExpanded.value = !isExpanded.value
}

const measureLoadTime = () => {
    const navigation = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming
    if (navigation) {
        loadTime.value = Math.round(navigation.loadEventEnd - navigation.fetchStart)
    }
}

const measureMemoryUsage = () => {
    if ('memory' in performance) {
        const memory = (performance as any).memory
        memoryUsage.value = Math.round(memory.usedJSHeapSize / 1024 / 1024)
    }
}

const measureFPS = () => {
    const now = performance.now()
    frameCount++

    if (now >= lastTime + 1000) {
        fps.value = Math.round((frameCount * 1000) / (now - lastTime))
        frameCount = 0
        lastTime = now
    }

    animationId = requestAnimationFrame(measureFPS)
}

const updateNetworkStatus = () => {
    networkStatus.value = navigator.onLine ? 'online' : 'offline'
}

const clearCache = () => {
    if ('caches' in window) {
        caches.keys().then(names => {
            names.forEach(name => {
                caches.delete(name)
            })
        })
    }

    // 清除 localStorage
    localStorage.clear()

    // 清除 sessionStorage
    sessionStorage.clear()

    console.log('缓存已清除')
}

const exportLogs = () => {
    const logs = {
        timestamp: new Date().toISOString(),
        loadTime: loadTime.value,
        memoryUsage: memoryUsage.value,
        fps: fps.value,
        networkStatus: networkStatus.value,
        userAgent: navigator.userAgent,
        url: window.location.href
    }

    const dataStr = JSON.stringify(logs, null, 2)
    const dataBlob = new Blob([dataStr], { type: 'application/json' })
    const url = URL.createObjectURL(dataBlob)

    const link = document.createElement('a')
    link.href = url
    link.download = `performance-log-${Date.now()}.json`
    link.click()

    URL.revokeObjectURL(url)
}

// 生命周期
onMounted(() => {
    // 只在开发环境显示
    if (isDev.value) {
        showMonitor.value = true

        // 测量页面加载时间
        measureLoadTime()

        // 开始监控
        measureFPS()

        // 监控内存使用（每5秒更新一次）
        const memoryInterval = setInterval(measureMemoryUsage, 5000)
        measureMemoryUsage()

        // 监控网络状态
        updateNetworkStatus()
        window.addEventListener('online', updateNetworkStatus)
        window.addEventListener('offline', updateNetworkStatus)

        // 清理函数
        onUnmounted(() => {
            if (animationId) {
                cancelAnimationFrame(animationId)
            }
            clearInterval(memoryInterval)
            window.removeEventListener('online', updateNetworkStatus)
            window.removeEventListener('offline', updateNetworkStatus)
        })
    }
})
</script>

<style lang="scss" scoped>
.performance-monitor {
    position: fixed;
    top: 10px;
    right: 10px;
    background: rgba(0, 0, 0, 0.8);
    color: white;
    border-radius: 8px;
    padding: 12px;
    font-size: 12px;
    z-index: 9999;
    min-width: 200px;
    backdrop-filter: blur(10px);

    .monitor-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;

        .toggle-btn {
            background: rgba(255, 255, 255, 0.2);
            border: none;
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 10px;

            &:hover {
                background: rgba(255, 255, 255, 0.3);
            }
        }
    }

    .monitor-content {
        .metric {
            display: flex;
            justify-content: space-between;
            margin-bottom: 4px;

            .label {
                opacity: 0.8;
            }

            .value {
                font-weight: bold;

                &.status-good {
                    color: #4caf50;
                }

                &.status-bad {
                    color: #f44336;
                }

                &.status-unknown {
                    color: #ff9800;
                }
            }
        }

        .actions {
            margin-top: 8px;
            display: flex;
            gap: 8px;

            .action-btn {
                background: rgba(255, 255, 255, 0.2);
                border: none;
                color: white;
                padding: 4px 8px;
                border-radius: 4px;
                cursor: pointer;
                font-size: 10px;
                flex: 1;

                &:hover {
                    background: rgba(255, 255, 255, 0.3);
                }
            }
        }
    }
}
</style>